/**
 * Copyright @ 2000 ysten Co. Ltd. 
 * All right reserved.     
 * @author: wangmin
 * date: 2016-05-21     
 */
package com.task.controller;

import com.task.domain.SysOperator;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;

/**
 * 主控制器
 */
@Controller
public class LoginController {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);


    @RequestMapping(value = "/to_welcome.html")
    public String toWelcome() {
        return "welcome";
    }

    @RequestMapping(value = "/login" ,method = RequestMethod.POST)
    public String login(SysOperator sysOperator, Model model, HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(sysOperator.getOperatorLoginName(), sysOperator.getOperatorPassword());
        try {
            subject.login(token);
//            return "system/index";
            return "redirect:/index";
        } catch(UnknownAccountException ue) {
            LOGGER.error("login error: {}",ue);
            token.clear();
            model.addAttribute("error", "登录失败，您输入的账号不存在");
            return "security/login";
        } catch(IncorrectCredentialsException ie) {
            LOGGER.error("login error: {}",ie);
            token.clear();
            model.addAttribute("username", sysOperator.getOperatorLoginName());
            model.addAttribute("error", "登录失败，密码不匹配");
            return "security/login";
        } catch(RuntimeException re) {
            LOGGER.error("login error: {}",re);
            token.clear();
            model.addAttribute("username", sysOperator.getOperatorLoginName());
            model.addAttribute("error", "登录失败");
            return "security/login";
        }
    }
}
